/*
 * create by lixy 20150323
 * Just for DMap(tuteng) Project
 * copyright@ 2015
 */
"use strict";
var $GLOBAL_USER = 'developer';

var app = angular.module('manager.star',
    ['ngRoute', 'ngSanitize',
        'ui.router',
        'angular-timeline',
        'angular-scroll-animate']);

app.config(function ($sceDelegateProvider) {
    $sceDelegateProvider.resourceUrlWhitelist([
        'self',
        'http://grafana-zp.58corp.com/**',
        'http://yunchuang.58corp.com/**',
        'https://wuba.xinghuo.58.com/**',
        '**',
        '*']);
});
app.config(['$routeProvider', function ($routeProvider) {
    $routeProvider
        .when('/sre', {
            templateUrl: './sre.html',
            controller: 'sreController'
        })
        .when('/star/dashboard', {
            templateUrl: './pages/dashboard.html',
            controller: 'dashboardController'
        })
        .when('/star/order/grafana_dapan/:id', {
            templateUrl: './pages/grafana_dapan.html',
            controller: 'grafanaDapanController'
        })
        // xinghuo_kanban
        .when('/sre/xinghuo_kanban/:id', {
            templateUrl: './pages/xinghuo_kanban.html',
            controller: 'xinghuoKanbanController'
        })

        // cost table
        .when('/star/cost/cost_report_team_list/:bucode/:period/:dt', {
            templateUrl: './pages/cost/cost_report_team_list.html',
            controller: 'costReportTeamListController'
        })
        .when('/star/cost/cost_report_list/:username/:period/:dt', {
            templateUrl: './pages/cost/cost_report_list.html',
            controller: 'costReportListController'
        })
        .when('/star/cost/cost_report_detail/:ownerId/:period/:dt', {
            templateUrl: './pages/cost/cost_report_detail.html',
            controller: 'costReportDetailController'
        })
        .when('/star/cost/cost_report_detail/:ownerId/:period/:dt/:basicPath', {
            templateUrl: './pages/cost/cost_report_detail.html',
            controller: 'costReportDetailController'
        })
        .when('/star/order/cost_report_detail_chart/:tag/:ownerId/:basicPath', {
            templateUrl: './pages/cost/cost_report_detail_chart.html',
            controller: 'costReportDetailChartController'
        })
        // cost task
        .when('/star/cost/cost_task_team_list/:bucode/:period/:dt', {
            templateUrl: './pages/cost/cost_task_team_list.html',
            controller: 'costTaskTeamListController'
        })
        .when('/star/cost/cost_task_list/:ownerId/:dt/:taskId', {
            templateUrl: './pages/cost/cost_task_list.html',
            controller: 'costTaskController'
        })
        .when('/star/cost/flink_cost_list', {
            templateUrl: './pages/cost/flink_cost_list.html',
            controller: 'flinkCostListController'
        })
        .when('/star/cost/other_cost_list', {
            templateUrl: './pages/cost/other_cost_list.html',
            controller: 'otherCostListController'
        })
        .when('/star/cost/cost_overview', {
            templateUrl: './pages/cost/cost_overview.html',
            controller: 'costOverviewController'
        })
        .when('/star/cost/cost_task_detail/:ownerId/:period/:dt', {
            templateUrl: './pages/cost/cost_task_detail.html',
            controller: 'costTaskDetailController'
        })
        .when('/star/order/cost_task_detail_chart/:taskId', {
            templateUrl: './pages/cost/cost_task_detail_chart.html',
            controller: 'costTaskDetailChartController'
        })

        .when('/sre/cost/resource_budget_mng_list/', {
            templateUrl: './pages/cost/resource_budget_mng_list.html',
            controller: 'resourceBudgetMngListController'
        })
        .when('/sre/cost/resource_budget_mng_edit/', {
            templateUrl: './pages/cost/resource_budget_mng_edit.html',
            controller: 'resourceBudgetMngEditController'
        })
        .when('/sre/cost/resource_budget_mng_edit/:id', {
            templateUrl: './pages/cost/resource_budget_mng_edit.html',
            controller: 'resourceBudgetMngEditController'
        })

        .when('/sre/cost/resource_group_mng_list/', {
            templateUrl: './pages/cost/resource_group_mng_list.html',
            controller: 'resourceGroupMngListController'
        })
        .when('/sre/cost/resource_group_mng_edit/', {
            templateUrl: './pages/cost/resource_group_mng_edit.html',
            controller: 'resourceGroupMngEditController'
        })
        .when('/sre/cost/resource_group_mng_edit/:id', {
            templateUrl: './pages/cost/resource_group_mng_edit.html',
            controller: 'resourceGroupMngEditController'
        })
        .when('/sre/cost/cost_quota_list', {
            templateUrl: './pages/cost/cost_quota_list.html',
            controller: 'costQuotaListController'
        })
        .when('/sre/cost/cost_quota_add/:id', {
            templateUrl: './pages/cost/cost_quota_add.html',
            controller: 'costQuotaAddController'
        })

        // 健康分管理
        .when('/star/cost/health_score_add/:tag/:appid/:name/:owner', {
            templateUrl: './pages/cost/health_score_add.html',
            controller: 'healthScoreAddController'
        })
        .when('/star/cost/health_score_list2/:tag/:dt/:orgCnName/:ownerId', {
            templateUrl: './pages/cost/health_score_list2.html',
            controller: 'healthScoreList2Controller'
        })
        .when('/star/cost/health_score_detail2/:tag/:dt/:appid', {
            templateUrl: './pages/cost/health_score_detail2.html',
            controller: 'healthScoreDetail2Controller'
        })
        .when('/star/cost/no_owner_table_info/', {
            templateUrl: './pages/cost/no_owner_table_info.html',
            controller: 'noOwnerTableInfoController2'
        })


//        .when('/star/cost/health_score_detail/:dt/:tableName', {
//            templateUrl: './pages/cost/health_score_detail.html',
//            controller: 'healthScoreDetailController'
//        })
//        .when('/star/cost/health_score_list/:dt/:orgCnName/:ownerId', {
//            templateUrl: './pages/cost/health_score_list.html',
//            controller: 'healthScoreListController'
//        })

//        .when('/star/cost/health_score_dashboard/:dt/:type', {
//            templateUrl: './pages/cost/health_score_dashboard.html',
//            controller: 'healthScoreDashboardController'
//        })

        // detection
        //        .when('/star/alert/detection_rule_list', {
        //            templateUrl: './pages/detection/detection_rule_list.html',
        //            controller: 'detectionRuleListController'
        //        })
        //        .when('/star/alert/detection_rule_add/:id', {
        //            templateUrl: './pages/detection/detection_rule_add.html',
        //            controller: 'detectionRuleAddController'
        //        })
        //        .when('/star/alert/detection_log_list', {
        //            templateUrl: './pages/detection/detection_log_list.html',
        //            controller: 'detectionLogListController'
        //        })
        //        .when('/star/alert/detection_log_detail/:id', {
        //            templateUrl: './pages/detection/detection_log_detail.html',
        //            controller: 'detectionLogDetailController'
        //        })


        //.when('/star/order/standard_checker_list', {
        //    templateUrl: './pages/detection/standard_checker_list.html',
        //    controller: 'standardCheckerListController'
        //})
        .when('/star/order/standard_rule_list', {
            templateUrl: './pages/detection/standard_rule_list.html',
            controller: 'standardRuleListController'
        })

        // help
        .when('/star/help/issue_list', {
            templateUrl: './pages/help/issue_list.html',
            controller: 'issueListController'
        })
        .when('/star/help/helpdoc_list', {
            templateUrl: './pages/help/helpdoc_list.html',
            controller: 'helpdocListController'
        })
        .when('/star/help/helpdoc_add/:id', {
            templateUrl: './pages/help/helpdoc_add.html',
            controller: 'helpdocAddController'
        })

        // metric
        .when('/star/metric/metric_kpi_master_list', {
            templateUrl: './pages/metric/metric_kpi_master_list.html',
            controller: 'metricKpiMasterListController'
        })
        .when('/star/metric/metric_kpi_master_add/:id', {
            templateUrl: './pages/metric/metric_kpi_master_add.html',
            controller: 'metricKpiMasterAddController'
        })
        .when('/star/metric/metric_kpi_detail_list/:kpiID', {
            templateUrl: './pages/metric/metric_kpi_detail_list.html',
            controller: 'metricKpiDetailListController'
        })
        .when('/star/metric/metric_kpi_detail_add/:id', {
            templateUrl: './pages/metric/metric_kpi_detail_add.html',
            controller: 'metricKpiDetailAddController'
        })

        .when('/star/metric/metric_list', {
            templateUrl: './pages/metric/metric_list.html',
            controller: 'metricListController'
        })
        .when('/star/metric/metric_add/:id', {
            templateUrl: './pages/metric/metric_add.html',
            controller: 'metricAddController'
        })
        .when('/star/metric/metric_report_detail/:metricID', {
            templateUrl: './pages/metric/metric_report_detail.html',
            controller: 'metricReportDetailController'
        })
        .when('/star/metric/metric_report_list', {
            templateUrl: './pages/metric/metric_report_list.html',
            controller: 'metricReportListController'
        })

        //
        //        // user
        //        .when('/star/user/user_list', {
        //            templateUrl: './pages/user/user_list.html',
        //            controller: 'userListController'
        //        })
        //        .when('/star/user/user_add/:id', {
        //            templateUrl: './pages/user/user_add.html',
        //            controller: 'userAddController'
        //        })
        //        .when('/star/user/user_group', {
        //            templateUrl: './pages/user/user_group.html',
        //            controller: 'userGroupController'
        //        })
        //        .when('/star/user/user_policy', {
        //            templateUrl: './pages/user/user_policy.html',
        //            controller: 'userPolicyController'
        //        })
        //        .when('/star/user/user_role', {
        //            templateUrl: './pages/user/user_role.html',
        //            controller: 'userRoleController'
        //        })
        //        .when('/star/user/user_capi', {
        //            templateUrl: './pages/user/user_capi.html',
        //            controller: 'userCapiController'
        //        })

        // yarn
        .when('/star/yarn/yarn_application_list/:cluster/:queue', {
            templateUrl: './pages/yarn/yarn_application_list.html',
            controller: 'yarnApplicationListController'
        })
        .when('/star/order/yarn_application_detail/:id', {
            templateUrl: './pages/yarn/yarn_application_detail.html',
            controller: 'yarnApplicationDetailController'
        })
        .when('/star/order/yarn_application_report/:cluster/:queue/:access/:ds0/:ds1', {
            templateUrl: './pages/yarn/yarn_application_report.html',
            controller: 'yarnApplicationReportController'
        })
        .when('/star/task/task_relation_info', {
            templateUrl: './pages/yarn/task_relation_info.html',
            controller: 'taskRelationListController'
        })
        .when('/star/task/dp_execute_log_list/:tableName', {
            templateUrl: './pages/yarn/dp_execute_log_list.html',
            controller: 'dpExecuteLogListController'
        })
        .when('/star/task/dp_execute_log_detail/:uniqueId', {
            templateUrl: './pages/yarn/dp_execute_log_detail.html',
            controller: 'dpExecuteLogDetailController'
        })
        .when('/star/order/project_list', {
            templateUrl: './pages/yarn/project_list.html',
            controller: 'projectListController'
        })
        .when('/star/order/project_add/:id', {
            templateUrl: './pages/yarn/project_add.html',
            controller: 'projectAddController'
        })
        .when('/star/order/yarn_quota_list/:cluster/:queue', {
            templateUrl: './pages/yarn/yarn_quota_list.html',
            controller: 'yarnQuotaListController'
        })
        .when('/star/order/yarn_quota_add/:id', {
            templateUrl: './pages/yarn/yarn_quota_add.html',
            controller: 'yarnQuotaAddController'
        })
        .when('/star/order/yarn_white_list/:cluster/:queue', {
            templateUrl: './pages/yarn/yarn_white_list.html',
            controller: 'yarnWhiteListController'
        })
        .when('/star/order/yarn_white_add/:id', {
            templateUrl: './pages/yarn/yarn_white_add.html',
            controller: 'yarnWhiteAddController'
        })
        .when('/star/order/hdfs_table_list/:cluster/:db', {
            templateUrl: './pages/yarn/hdfs_table_list.html',
            controller: 'hdfsTableListController'
        })
        .when('/star/order/hdfs_table_detail/:id', {
            templateUrl: './pages/yarn/hdfs_table_detail.html',
            controller: 'hdfsTableDetailController'
        })
        .when('/star/order/owner_queue_list', {
            templateUrl: './pages/yarn/owner_queue_list.html',
            controller: 'ownerQueueListController'
        })

        .when('/star/task/timeout_task_list', {
            templateUrl: './pages/yarn/timeout_task_list.html',
            controller: 'timeoutTaskListController'
        })

        // report manage
        .when('/star/report/email_report_list', {
            templateUrl: './pages/report/email_report_list.html',
            controller: 'emailReportListController'
        })
        .when('/star/report/email_report_add/:id', {
            templateUrl: './pages/report/email_report_add.html',
            controller: 'emailReportAddController'
        })
        .when('/star/report/xinghuo_report_list', {
            templateUrl: './pages/report/xinghuo_report_list.html',
            controller: 'xinghuoReportListController'
        })
        .when('/star/report/xinghuo_report_add/:id', {
            templateUrl: './pages/report/xinghuo_report_add.html',
            controller: 'xinghuoReportAddController'
        })
        .when('/star/report/xinghuo', {
            templateUrl: './pages/report/xinghuo.html',
            controller: 'xinghuoController'
        })
        .when('/sre/mng/hdfs_path_list/:type/:project', {
            templateUrl: './pages/mng/hdfs_path_list.html',
            controller: 'hdfsPathListController'
        })
        .when('/sre/mng/hdfs_path_edit/:type/:id', {
            templateUrl: './pages/mng/hdfs_path_edit.html',
            controller: 'hdfsPathEditController'
        })

        .when('/star/report/zhibiao_manage_list', {
            templateUrl: './pages/report/zhibiao_manage_list.html',
            controller: 'zhibiaoManageListController'
        })
        .when('/star/report/zhibiao_manage_add/:id', {
            templateUrl: './pages/report/zhibiao_manage_add.html',
            controller: 'zhibiaoManageAddController'
        })
        .when('/star/report/zhibiao', {
            templateUrl: './pages/report/zhibiao.html',
            controller: 'zhibiaoController'
        })

        .when('/star/metric/data_metric', {
            templateUrl: './pages/metric/data_metric.html',
            controller: 'dataMetricController'
        })
        .when('/star/metric/data_metric_list', {
            templateUrl: './pages/metric/data_metric_list.html',
            controller: 'dataMetricListController'
        })
        .when('/star/metric/data_metric_add/:id', {
            templateUrl: './pages/metric/data_metric_add.html',
            controller: 'dataMetricAddController'
        })
        .when('/sre/config/olap_config', {
            templateUrl: './pages/config/olap_config.html',
            controller: 'olapConfigListController'
        })
        .when('/sre/config/olap_config/add', {
            templateUrl: './pages/config/olap_add.html',
            controller: 'olapConfigAddController'
        })
        .when('/sre/config/olap_config/edit/:id', {
            templateUrl: './pages/config/olap_add.html',
            controller: 'olapConfigEditController'
        })

        .when('/sre/config/rt_topic_config_list', {
            templateUrl: './pages/config/rt_topic_config_list.html',
            controller: 'rtTopicConfigListController'
        })
        .when('/sre/config/rt_topic_config_edit/:id', {
            templateUrl: './pages/config/rt_topic_config_edit.html',
            controller: 'rtTopicConfigEditController'
        })
        .when('/sre/config/rt_topic_config_edit/', {
            templateUrl: './pages/config/rt_topic_config_edit.html',
            controller: 'rtTopicConfigEditController'
        })
        .when('/sre/dqc/dqc_config', {
            templateUrl: './pages/dqc/dqc_config.html',
            controller: 'dqcConfigListController'
        })
        .when('/sre/dqc/dqc_config/add', {
            templateUrl: './pages/dqc/dqc_add.html',
            controller: 'dqcConfigAddController'
        })
        .when('/sre/dqc/dqc_config/edit/:id', {
            templateUrl: './pages/dqc/dqc_add.html',
            controller: 'dqcConfigEditController'
        })
        .when('/sre/dqc/dqc_check_task_config_list', {
            templateUrl: './pages/dqc/dqc_check_task_config_list.html',
            controller: 'dqcCheckTaskConfigListController'
        })
        .when('/sre/dqc/dqc_check_config/sla_check/:id', {
            templateUrl: './pages/dqc/dqc_sla_check_config.html',
            controller: 'dqcSlaCheckConfigController'
        })
        .when('/sre/dqc/dqc_check_config/data_count_check/:id', {
            templateUrl: './pages/dqc/dqc_data_count_check_config.html',
            controller: 'dqcCataCountCheckConfigController'
        })
        .when('/sre/dqc/dqc_check_config/join_radio_check/:id', {
            templateUrl: './pages/dqc/dqc_join_radio_check_config.html',
            controller: 'dqcJoinRadioCheckConfigController'
        })
        .when('/sre/dqc/dqc_check_config/field_error_check/:id', {
            templateUrl: './pages/dqc/dqc_field_error_check_config.html',
            controller: 'dqcFieldErrorCheckConfigController'
        })


        .when('/sre/config/task_baseline_list', {
            templateUrl: './pages/config/task_baseline_list.html',
            controller: 'taskBaselineListController'
        })
        .when('/sre/config/task_baseline_add/:id', {
            templateUrl: './pages/config/task_baseline_add.html',
            controller: 'taskBaselineAddController'
        })



        // 指标计算配置
        .when('/star/metric/rt_metric_sync_config_list', {
            templateUrl: './pages/metric/rt_metric_sync_config_list.html',
            controller: 'rtMetricSyncConfigController'
        })
        .when('/star/metric/rt_metric_sync_config/:id', {
            templateUrl: './pages/metric/rt_metric_sync_config.html',
            controller: 'rtMetricSyncConfigMngController'
        })
        .when('/star/metric/rt_metric_sync_config/', {
            templateUrl: './pages/metric/rt_metric_sync_config.html',
            controller: 'rtMetricSyncConfigMngController'
        })

        // 埋点管理
        .when('/star/spm/spm_list', {
            templateUrl: './pages/spm/spm_list.html',
            controller: 'spmListController'
        })

        // 看板
        .when('/star/metric2/zhibiao/:id/:nodeId', {
            templateUrl: './pages/metric2/zhibiao.html',
            controller: 'zhibiaoController'
        })
        .when('/sre/metric2/field_monitor/:metric/:biz/:actionType/:logsource', {
            templateUrl: './pages/metric2/field_monitor.html',
            controller: 'fieldMonitorController'
        })

        .otherwise({
            redirectTo: '/sre'
        });
}]);

//权限校验
app.run(['$rootScope', '$location', 'userPermissionCheckService', function ($rootScope, $location, userPermissionCheckService) {

    /* 监听路由的状态变化 */
    $rootScope.$on('$routeChangeStart', function (event, msg) {

        console.log('routeChangeStart start');
        var permissionUrl = $location.$$absUrl.split($location.$$host + ':' + $location.$$port)[1]
        if ($location.$$port == 80) {
            permissionUrl = $location.$$absUrl.split($location.$$host)[1]
        }
        if (permissionUrl == '/star/index.html#/star/no_permission') {
            return
        }

        var param = {};
        param.permissionUrl = permissionUrl
        var hasPermission = true
        var procFn = function (response) {
            if (response.data == null || typeof (response.data) == 'undefined') {
                return
            }
            hasPermission = response.data
            if (hasPermission) {
                console.log(permissionUrl + ' pass')
                return
            } else {
                console.log(permissionUrl + ' not pass')
                window.location.href = "/star/index.html#/star/no_permission";
            }
        };
        var errorFn = function (result) {
            console.log('login error: ' + result);
            console.error('permission validate error');
        };
        userPermissionCheckService.permissionValidate(param, procFn, errorFn);
        console.log('routeChangeStart end');
    });

    $rootScope.$on('$routeChangeSuccess', function (evt, current, previous) {
        let permissionUrl = $location.$$absUrl.split($location.$$host + ':' + $location.$$port)
        console.log('route have already changed ：' + permissionUrl);
        if(typeof($GLOBAL_USER)!='undefined') {
            watermark({ watermark_txt: $GLOBAL_USER });
        }
    });

}])

/* Services */
app.service('userPermissionCheckService', ['ajaxService', function (ajaxService) {

    this.permissionValidate = function (params, successFunction, errorFunction) {
        $.ajax({
            url: "/star/api/basic-service/v1/user_permission/validate.do",//请求路径
            async: false,
            data: JSON.stringify(params),
            type: "POST",//GET
            contentType: 'application/json',
            dataType: "JSON",//需要返回JSON对象(如果Ajax返回的是手动拼接的JSON字符串,需要Key,Value都有引号)
            success: function (response, status, headers, config) {
                if ((response.code == '00000001' || response.code == '-100') && response.data != null && response.data.redirectUrl != null) {
                    window.location = response.data.redirectUrl;
                } else {
                    successFunction(response, status);
                }
            },
            error: function (response) {
                if (response.IsAuthenicated == false) { window.location = "/index.html"; }
                errorFunction(response);
            }
        })

    };

}]);

var user_cookie_tag = "ac_key";
/* Controllers */
app.controller('index', ['$scope', '$location', '$rootScope', '$routeParams', 'indexService', function ($scope, $location, $rootScope, $routeParams, indexService) {
    var vm = $scope.vm = {};

    vm.p = {};
    vm.result = {};

    var errorFn = function (result) {
        alert(result);
    };
    $scope.pingDetail = function () {
        var vm = $scope.vm;
        vm.result.ms = "...";
        var params = {};
        var procFn = function (response) {
            vm.result.ms = response.ms;
            var data = response.data;
            if (data == null) return;
            $GLOBAL_USER = data[0].userName;

            watermark({ watermark_txt: $GLOBAL_USER });
        };
        indexService.pingDetail(params, procFn, errorFn);
    };
    $scope.initializeController = function () {
        vm.result.ms = '';
        $scope.pingDetail();
    };
    $scope.initializeController();
}]);
/* Services */
app.service('indexService', ['ajaxService', function (ajaxService) {
    this.list = function (params, successFunction, errorFunction) {
        ajaxService.AjaxGetWithData(params, "./api/v1/bibcp/xxx/list", successFunction, errorFunction);
    };
    this.pingDetail = function (params, successFunction, errorFunction) {
        ajaxService.AjaxPost(params, "/star/api/basic-service/v1/aaa/pingDetail.do", successFunction, errorFunction);
    };
}]);


function formatColor(value) {
    var color = colorByVal(value);
    return ['<font color="', color, '">', value, '</font>'].join('');
}
function formatColorCtx(value, color) {
    return ['<font color="', color, '">', value, '</font>'].join('');
}


function serialFormatter(value, row, index) {
    return index + 1;
}

app.filter('contentFmt1', function () {
    return function (input) { // input是我们传入的字符串
        var strs = input.split(",");
        return (strs.length > 1) ? strs[0] : input;
    }
});
app.filter('contentFmt2', function () {
    return function (input) { // input是我们传入的字符串
        var strs = input.split(",");
        return (strs.length > 1) ? strs[1] : input;
    }
});


function crudActionFmt(value, row, index) {
    if (value == null) return "-";
    switch (value) {
        //case 0:
        //    return "新建";
        //    break;
        //case 1:
        //    return "修改";
        //    break;
        case 0:
        case 1:
            return "有效";
            break;
        case 2:
            //return "删除";
            return "无效";
            break;
        case 3:
            return "停用";
            break;
        case 4:
            return "提交审批";
        case 5:
            return "审批通过";
            break;
        case 6:
            return "已运行";
        case 7:
            return "已停止";
        default:
            break;
    }
    return value;
}

function strFormatter(value, row, index) {
    if (value == null) return null;
    return value + "";
}


function orderSubTypeFormatter(value, row, index) {
    if (value == null) return null;
    var ret = '';
    if (value == 0) {
        ret = '堂食';//formatColorCtx('堂食','blue');
    } else if (value == 20) {
        ret = '外卖';//formatColorCtx('外卖','green');
    } else if (value == 21) {
        ret = '自提';//formatColorCtx('自提','yellow');
    } else {
        ret = formatColorCtx('未知:' + value, 'red');
    }
    return ret;
}


function reasonFormatter(value, row, index) {
    if (value == null) return null;
    return formatColorCtx(value, 'red');
}



app.filter('checkReasonIDFormatter', function () {
    return function (value) { // value是我们传入的字符串
        return checkReasonIDFormatter(value, null, null);
    }
});
app.filter('hllDtFormatter', function () {
    return function (value) { // value是我们传入的字符串
        return hll2StdTime(value);
    }
});


app.filter("countNameFmt", function () {
    return function (input) { // input是我们传入的字符串
        if (input == null) return null;
        return quataLineName(input);
    }
});
app.filter("countZhuNameFmt", function () {
    return function (input) { // input是我们传入的字符串
        if (input == null) return null;
        return quataZhuName(input);
    }
});
app.filter("linkFmt", function () {
    return function (input) { // input是我们传入的字符串
        if (input == null) return null;
        var keys = input.rowkey.split("^");
        var resonId = keys[keys.length - 1];
        return resonId
    }
});

app.filter("dateFmt", function () {
    return function (input) { // input是我们传入的字符串
        if (input == null) return null;
        var length = input.cntList.length;
        var date = input.cntList[length - 1][0];
        return date
    }
});

app.filter("bigNumFmt", function () {
    return function (input) { // input是我们传入的字符串
        return bigNumFmt(input)
    }
});

// 异常ID可视化
function checkReasonIDFormatter(value, row, index) {
    if (value == null) return null;
    return [value, '-', reasonName(value)].join('');
}


function contextFormatter(value, row, index) {
    if (value == null) return null;
    var ret = '';
    var len = value.length;
    var step = 80;
    for (var i = 0; i < len; i += step) {
        ret += value.substr(i, step);
        ret += "<br/>"
    }
    return ret;
}

function orderKeyFormatter(value, row, index) {// /profiling/:groupID/:shopID/:saasOrderID
    return ['<a href="#/profiling/', row.groupID, '/', row.shopID, '/', value, '" target="_blank">', value, '</a>'].join('');
}

function licenseCheckFmt(value, row, index) {// /profiling/:groupID/:shopID/:saasOrderID
    return ['<a href="#/star/license/license_check/', value, '" target="_blank">', value, '</a>'].join('');
}

function orderIDFmt(value, row, index) {// /profiling/:groupID/:shopID/:saasOrderID
    return ['<a href="#/star/order/mall_order_detail/', value, '" target="_blank">', value, '</a>'].join('');
}

function queryLicenseFmt(value, row, index) {// /profiling/:groupID/:shopID/:saasOrderID
    return ['<a href="#/star/order/mall_order_detail/', value, '" target="_blank">', "开户进度", '</a>'].join('');
}

function merchantDetailFmt(value, row, index) {// /profiling/:groupID/:shopID/:saasOrderID
    return ['<a href="#/star/merchant/merchant_detail/', value, '" target="_blank">', "开户详情", '</a>'].join('');
}

function continueRegisterFmt(value, row, index) {// /profiling/:groupID/:shopID/:saasOrderID
    return ['<a href="" ng-click="continueRegister(', value, ')">', "失败修复", '</a>'].join('');
}


function moneyFixedFmt(value, row, index) {
    if (value == null) return null;
    return value.toFixed(2);
}




function getTsBefore(gap) {
    if (gap == null || gap == 0) gap = 0;
    var today = new Date();
    var before = new Date();
    before.setTime(today.getTime() - 1000 * gap);
    var strYear = before.getFullYear();
    var strDay = before.getDate();
    if (strDay < 10) {
        strDay = "0" + strDay;
    }
    var strMonth = before.getMonth() + 1;
    if (strMonth < 10) {
        strMonth = "0" + strMonth;
    }
    var strHour = before.getHours();
    if (strHour < 10) {
        strHour = "0" + strHour;
    }
    var strMin = before.getMinutes();
    if (strMin < 10) {
        strMin = "0" + strMin;
    }
    var strSec = before.getSeconds();
    if (strSec < 10) {
        strSec = "0" + strSec;
    }
    return ("" + strYear + strMonth + strDay + strHour + strMin + strSec);
}


function getHMBefore(gap) {
    if (gap == null || gap == 0) gap = 0;
    var today = new Date();
    var before = new Date();
    before.setTime(today.getTime() - 1000 * 60 * gap);
    var strYear = before.getFullYear();
    var strDay = before.getDate();
    if (strDay < 10) {
        strDay = "0" + strDay;
    }
    var strMonth = before.getMonth() + 1;
    if (strMonth < 10) {
        strMonth = "0" + strMonth;
    }
    var strHour = before.getHours();
    if (strHour < 10) {
        strHour = "0" + strHour;
    }
    var strMin = before.getMinutes();
    if (strMin < 10) {
        strMin = "0" + strMin;
    }
    return ("" + strYear + strMonth + strDay + strHour + strMin);
}

function getHBefore(gap) {
    if (gap == null || gap == 0) gap = 0;
    var today = new Date();
    var before = new Date();
    before.setTime(today.getTime() - 1000 * 60 * 60 * gap);
    var strYear = before.getFullYear();
    var strDay = before.getDate();
    if (strDay < 10) {
        strDay = "0" + strDay;
    }
    var strMonth = before.getMonth() + 1;
    if (strMonth < 10) {
        strMonth = "0" + strMonth;
    }
    var strHour = before.getHours();
    if (strHour < 10) {
        strHour = "0" + strHour;
    }
    return ("" + strYear + strMonth + strDay + strHour);
}

function getHMDefault(gap) {
    if (gap == null || gap == 0) gap = 0;
    var today = new Date();
    var before = new Date();
    before.setTime(today.getTime() - 1000 * 60 * 60 * gap);
    var strYear = before.getFullYear();
    var strDay = before.getDate();
    if (strDay < 10) {
        strDay = "0" + strDay;
    }
    var strMonth = before.getMonth() + 1;
    if (strMonth < 10) {
        strMonth = "0" + strMonth;
    }
    return ("" + strYear + strMonth + strDay + "0000");
}

//长字符串表格截取显示
function longContentFmt(value, row, index) {
    if (value.length > 20) {
        // $("#message-text").val(value);
        return value.substring(0, 20) + "..." + "<a data-toggle=\"modal\" data-target=\"#exampleModal\" onclick=\"showLongContent(" + index + ")\" href=\"javascript::void(0)\">[详情]</a>";
    } else {
        return "<div style=\"font-family:'微软雅黑'\">" + value + "</div>";
    }
}

//使用弹框显示所有内容
function showLongContent(index) {
    var element = angular.element($("#message-text"));
    var scope = element.scope();
    scope.$apply(function () {
        scope.index = index;
    });
}

function delete_confirm() {
    return confirm("删除是不可恢复的，你确认要删除吗？");
}

function numberFmt(value, row, index) {
    if (!value) return '';
    return value.replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,');
}

function add0(m) {
    return m < 10 ? '0' + m : m
}

function dateFormat(value, row, index) {
    //shijianchuo是整数，否则要parseInt转换
    var time = new Date(value);
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s);
}

function hllCurrentTime() {
    //shijianchuo是整数，否则要parseInt转换
    var time = new Date();
    var y = time.getFullYear();
    var m = time.getMonth() + 1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return y + add0(m) + add0(d) + add0(h) + add0(mm) + add0(s);
}

//自定义指令实现ng-repeat完成后执行repeatFinish方法
app.directive('repeatFinish', function () {
    return {
        link: function (scope, element, attr) {
            console.log(scope.$index);
            if (scope.$last == true) {
                console.log('ng-repeat over, will draw chart.');
                scope.$eval(attr.repeatFinish)
            }
        }
    }
});
// hll时间转化为std时间
function hll2StdTime(v) {
    if (v == null) return null;
    v += "";// 将对象转为字符串
    if (v.length == 14) {// 20181112155301
        return [v.substr(0, 4), '-', v.substr(4, 2), '-', v.substr(6, 2), ' ', v.substr(8, 2), ':', v.substr(10, 2), ':', v.substr(12, 2)].join('');
    } else if (v.length == 12) {// 201811121553
        return [v.substr(0, 4), '-', v.substr(4, 2), '-', v.substr(6, 2), ' ', v.substr(8, 2), ':', v.substr(10, 2)].join('');
    } else if (v.length == 8) {// 20181112
        return [v.substr(0, 4), '-', v.substr(4, 2), '-', v.substr(6, 2)].join('');
    }
}
function hll2StdTimeFmt(value, row, index) {
    // var sourcesize = {data:value};
    return hll2StdTime(value);
}
function objFmt(value, row, index) {
    return JSON.stringify(value);
}


function statusFormatter(value, row, index) {
    if (value == null) {
        return "-";
    }
    switch (value) {
        case 0:
            return "未使用";
        case 1:
            return "已使用";
        default:
            return "-";
    }
}

function productDetailFmt(value, row, index) {
    if (value == null) {
        return "-";
    }
    var arr = [];
    var items = value.split(';');
    for (var i = 0; i < items.length; ++i) {
        var it = items[i];
        var vals = it.split(',');
        //var str = ['[',vals[0],']',vals[3],':',vals[2]].join('');
        var str = [vals[3], ':', vals[2]].join('');
        arr.push(str);
    }
    return arr.join('<br/>');
}



function subBillStatusFormatter(value, row, index) {
    if (value == null) {
        return "-";
    }
    switch (value) {
        case 0:
        case 1:
            return "待接单";
        case 2:
            return "待发货";
        case 3:
            return "已收货";
        case 4:
            return "待结算";
        case 5:
            return "已完成";
        case 6:
            return "已取消";
        case 7:
            return "拒收";
        default:
            return "-";
    }
}

function payTypeFormatter(value, row, index) {
    if (value == null) {
        return "-";
    }
    switch (value) {
        case 0:
        case 1:
            return "货到付款";
        case 2:
            return "账期支付";
        case 3:
            return "线上支付";
        default:
            return "-";
    }
}

function isTestFmt(value, row, index) {
    if (value == null) {
        return "-";
    }
    var typeName = '';
    switch (value) {
        case 0:
            typeName = "正常";
            break;
        case 1:
            typeName = "<font color='red'>测试</font>";
            break;
        default:
            typeName = "-";
            break;
    }
    return typeName;
    //return [value,'-',typeName].join('')
}

function productDetailListJsonFmt(value, row, index) {
    if (value == null || value == 'null') {
        return "-";
    }
    var rows = [];
    var items = JSON.parse(value);
    for (var i = 0; i < items.length; ++i) {
        var data = items[i];
        rows.push(['产品名称：', data['productName'], ", 出库数量：", data['productNumber']].join(''));
    }
    return rows.join('<br/>')
}


function reasonTypeFormatter(value, row, index) {// /profiling/:groupID/:shopID/:saasOrderID
    return [value, '<a href="http://help.hualala.com/pages/viewpage.action?pageId=3146289" target="_blank">帮助</a>'].join('');
}

//function transOrderID2LicenseFmt(value, row, index) {// /profiling/:groupID/:shopID/:saasOrderID
//    return ['<a href="#/star/license/license_list/', value, '" target="_blank">', value , '</a>'].join('');
//}


function deliverOptFmt(value, row, index) {
    if (value == null) {
        return "-";
    }
    return [
        '<a href="#/star/order/tfz_order_deliver_add/', value, '/', row.transOrderID, '" target="_blank">', "<u>编辑查看</u>", '</a>',
        '<a href="#/star/order/tfz_order_deliver_review/', value, '/', row.transOrderID, '" target="_blank">', " <u>申请提交</u>", '</a>'
    ].join('');
}

function productIDFmt(value, row, index) {
    return ['<a href="#/star/product/product_add/', value, '" target="_blank"> ', "编辑", '</a>'].join('');
}
function userIDFmt(value, row, index) {
    return ['<a href="#/star/user/user_add/', value, '" target="_blank"> ', "编辑", '</a>'].join('');
}


var datetimePicker = function (pickerId, inputId) {
    $(function () {
        //初始化日期控件
        $('#' + pickerId).datetimepicker({
            format: "yyyy-mm-dd",
            weekStart: 1,
            todayBtn: 1,
            autoclose: 1,
            todayHighlight: 1,
            startView: 2,
            forceParse: 0,
            startDate: "2015-01-01",
            minView: 2,
            showMeridian: 1,
            language: "zh-CN"
        });
        //初始化日期控件的输入框
        $('#' + inputId).val(getDateStr(-1));
    });
};

Date.prototype.add = function (part, value) {
    value *= 1;
    if (isNaN(value)) {
        value = 0;
    }
    switch (part) {
        case "y":
            this.setFullYear(this.getFullYear() + value);
            break;
        case "m":
            this.setMonth(this.getMonth() + value);
            break;
        case "d":
            this.setDate(this.getDate() + value);
            break;
        case "h":
            this.setHours(this.getHours() + value);
            break;
        case "n":
            this.setMinutes(this.getMinutes() + value);
            break;
        case "s":
            this.setSeconds(this.getSeconds() + value);
            break;
        default:

    }
};

Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1,
        // month
        "d+": this.getDate(),
        // day
        "h+": this.getHours(),
        // hour
        "m+": this.getMinutes(),
        // minute
        "s+": this.getSeconds(),
        // second
        "q+": Math.floor((this.getMonth() + 3) / 3),
        // quarter
        "S": this.getMilliseconds()
        // millisecond
    };
    if (/(y+)/.test(format) || /(Y+)/.test(format)) {
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};


function getNowFormatDate(diff) {
    var day = new Date();
    day.setDate(day.getDate() + diff);
    var Year = 0;
    var Month = 0;
    var Day = 0;
    var CurrentDate = "";
    Year = day.getFullYear();//支持IE和火狐浏览器.
    Month = day.getMonth() + 1;
    Day = day.getDate();
    CurrentDate += Year;
    if (Month >= 10) {
        CurrentDate += Month;
    }
    else {
        CurrentDate += "0" + Month;
    }
    if (Day >= 10) {
        CurrentDate += Day;
    }
    else {
        CurrentDate += "0" + Day;
    }
    return CurrentDate;
}


function isTestUserFmt(value, row, index) {
    if (value == null) {
        return "-";
    }
    switch (value) {
        case 0:
            return "正式";
        case 1:
            return "测试";
        default:
            return "-";
    }
}

function userStatusFmt(value, row, index) {
    if (value == null) {
        return "-";
    }
    switch (value) {
        case 0:
            return "离职";
        case 1:
            return "在岗";
        default:
            return "-";
    }
}
function rowActionFmt(value, row, index) {
    if (value == null) {
        return "-";
    }
    switch (value) {
        case 0:
            return "新建";
        case 1:
            return "修改";
        case 2:
            return "删除";
        default:
            return "-";
    }
}



function toThousands(num) {
    //var result = '', counter = 0;
    //num = (num || 0).toString();
    //for (var i = num.length - 1; i >= 0; i--) {
    //    counter++;
    //    result = num.charAt(i) + result;
    //    if (!(counter % 3) && i != 0) { result = ',' + result; }
    //}
    //return result;
    var s = (num || 0).toString();
    var l = s.split(".")[0].split("").reverse();
    var r = s.split(".")[1];
    var t = "";
    for (var i = 0; i < l.length; i++) {
        t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
    }
    if (r) {
        return t.split("").reverse().join("") + "." + r;
    } else {
        return t.split("").reverse().join("");
    }
}

function toPencent(num, row, index) {
    if (num == null) {
        return "-";
    }
    return (parseFloat(num) * 100).toFixed(2) + '%'
}

function loadingTemplate(message) {
    return '<i class="fa fa-spinner fa-spin fa-fw fa-2x"></i>'
}

function tableLoadingTemplate(message) {
    // return '<div style="width: 100%;height: 100%;padding: 0;margin: 0;" class="ph-item"><div style="width: 100%;height: 100%;padding: 0;margin: 0;" class="ph-picture"></div></div>'
    // return '<div class="ph-item"><div class="ph-picture"></div></div>'
    return '<i class="fa fa-spinner fa-spin fa-fw fa-2x"></i>'
}
